<template>
  <div class="user-manage">
    <el-card class="table-card">
      <div class="table-header">
        <div class="search-area">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名称"
            clearable
            class="search-input"
          />
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="showAdvancedSearch">
            <el-icon><Setting /></el-icon>高级搜索
          </el-button>
        </div>
        <div class="action-area">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button 
            type="danger" 
            :disabled="!selectedIds.length" 
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="用户名称" prop="username" />
        <el-table-column label="登录名" prop="loginName" />
        <el-table-column label="昵称" prop="nickName" />
        <el-table-column label="手机号码" prop="phoneNumber" />
        <el-table-column label="邮箱" prop="userEmail" show-overflow-tooltip />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.userStatus === '0' ? 'success' : 'danger'">
              {{ row.userStatus === '0' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="registeredTime" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 高级搜索对话框 -->
    <el-dialog
      title="高级搜索"
      v-model="searchDialogVisible"
      width="800px"
      append-to-body
    >
      <el-form
        ref="advancedSearchForm"
        :model="advancedQueryParams"
        label-width="100px"
        class="advanced-search-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名称">
              <el-input v-model="advancedQueryParams.username" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录名">
              <el-input v-model="advancedQueryParams.loginName" placeholder="请输入登录名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input v-model="advancedQueryParams.nickName" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">
              <el-input v-model="advancedQueryParams.phoneNumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="advancedQueryParams.userEmail" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="advancedQueryParams.userSex" placeholder="请选择性别" clearable>
                <el-option label="男" value="1" />
                <el-option label="女" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="advancedQueryParams.userStatus" placeholder="请选择状态" clearable>
                <el-option label="正常" value="0" />
                <el-option label="禁用" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="searchDialogVisible = false">取 消</el-button>
          <el-button @click="resetAdvancedSearch">重 置</el-button>
          <el-button type="primary" @click="handleAdvancedSearch">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        label-width="100px"
      >
        <el-form-item label="用户名称">
          <el-input v-model="userForm.username" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="登录名">
          <el-input v-model="userForm.loginName" placeholder="请输入登录名" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userForm.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="userForm.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.userEmail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userForm.userSex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="userForm.userStatus">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { getUserList, addUser, updateUser, deleteUsers } from '@/api/system/user'
import type { SysUser, PageQuery } from '@/types/user'

// 查询参数
const queryParams = reactive<Partial<SysUser> & PageQuery>({
  pageNum: 1,
  pageSize: 10,
  username: '',
  phoneNumber: '',
  userStatus: ''
})

// 表格数据
const loading = ref(false)
const userList = ref<SysUser[]>([])
const total = ref(0)
const selectedIds = ref<string[]>([])

// 对话框数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const userFormRef = ref()
const userForm = ref<Partial<SysUser>>({
  username: '',
  loginName: '',
  nickName: '',
  phoneNumber: '',
  userEmail: '',
  userSex: '1',
  userStatus: '0'
})

// 高级搜索相关
const searchDialogVisible = ref(false)
const dateRange = ref<[string, string]>(['', ''])
const advancedQueryParams = reactive<Partial<SysUser>>({
  username: '',
  loginName: '',
  nickName: '',
  phoneNumber: '',
  userEmail: '',
  userSex: '',
  userStatus: '',
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as any, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取用户列表
const getList = async () => {
  try {
    loading.value = true
    const { pageNum, pageSize, ...params } = queryParams
    const res = await getUserList({
      data: params,
      params: { pageNum, pageSize }
    })
    if (res.code === 200 && res.data) {
      userList.value = Array.isArray(res.data) ? res.data : res.data.records || []
      total.value = res.data.total || userList.value.length
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.username = ''
  queryParams.phoneNumber = ''
  queryParams.userStatus = ''
  handleQuery()
}

// 表格多选框选中数据
const handleSelectionChange = (selection: SysUser[]) => {
  selectedIds.value = selection.map(item => item.userId)
}

// 新增按钮点击
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  userForm.value = {}
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row: SysUser) => {
  dialogTitle.value = '编辑用户'
  userForm.value = { ...row }
  dialogVisible.value = true
}

// 删除按钮点击
const handleDelete = async (row: SysUser) => {
  await ElMessageBox.confirm('确认要删除该用户吗？', '警告', {
    type: 'warning'
  })
  try {
    const res = await deleteUsers([row.userId])
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    console.error('删除用户失败:', error)
  }
}

// 批量删除按钮点击
const handleBatchDelete = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  await ElMessageBox.confirm(
    `确认要删除这 ${selectedIds.value.length} 个用户吗？`,
    '警告',
    { type: 'warning' }
  )
  try {
    const res = await deleteUsers(selectedIds.value)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getList()
    }
  } catch (error) {
    console.error('批量删除用户失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const api = userForm.value.userId ? updateUser : addUser
    const res = await api(userForm.value)
    if (res.code === 200) {
      ElMessage.success(userForm.value.userId ? '修改成功' : '新增成功')
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('保存用户失败:', error)
  }
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getList()
}

// 显示高级搜索
const showAdvancedSearch = () => {
  Object.assign(advancedQueryParams, queryParams)
  searchDialogVisible.value = true
}

// 重置高级搜索
const resetAdvancedSearch = () => {
  Object.keys(advancedQueryParams).forEach(key => {
    advancedQueryParams[key] = ''
  })
  dateRange.value = ['', '']
}

// 确认高级搜索
const handleAdvancedSearch = () => {
  Object.assign(queryParams, advancedQueryParams)
  if (dateRange.value[0] && dateRange.value[1]) {
    queryParams.startTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
  }
  searchDialogVisible.value = false
  handleQuery()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.user-manage {
  padding: 20px;
  
  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .search-area {
        display: flex;
        gap: 8px;
        
        .search-input {
          width: 240px;
        }
      }
      
      .action-area {
        display: flex;
        gap: 8px;
      }
    }
  }
}

.advanced-search-form {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}
</style> 